package com.billionsfinance.hessian.common.zookeeper.server;

import com.billionsfinance.hessian.model.ServerInfo;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.UUID;

/**
 * @ ClassName: ServerSideRegisterThread.java
 * @ Author: WeiHui-Z
 * @ Date: 2016/11/23 12:37
 * @ Version: v1.0.0
 */
public class ServerSideRegisterThread implements Runnable {

    private static final Logger LOGGER = LoggerFactory.getLogger(ServerSideRegisterThread.class);

    private CuratorFramework curatorFramework;

    private String service;

    private String key;

    private String data;

    ServerSideRegisterThread(CuratorFramework curatorFramework, ServerInfo serverInfo) {
        this.curatorFramework = curatorFramework;
        this.service = serverInfo.getPath();
        this.key = UUID.randomUUID().toString();
        this.data = serverInfo.getData();
    }

    @Override
    public void run() {
        LOGGER.info("begin register service : {}", service);
        //注册次数----注册7次还不成功就不再注册.
        int count = 0;
        while (count <= 7) {
            try {
                // 先保证此永久节点存在
                if (curatorFramework.checkExists().forPath(service) == null) {
                    curatorFramework.create().creatingParentContainersIfNeeded().forPath(service);
                }
                // 然后正式注册---临时节点
                // 构造临时节点
                curatorFramework.create().creatingParentContainersIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(service + "/" + key, data.getBytes("UTF-8"));
                // 注册成功，就跳出循环，表示此runnable结束
                LOGGER.info("succeed to register service: {}", service);
                return;
            } catch (Exception e) {
                LOGGER.error("failed to register service: " + service, e);
                count++;
                if (count > 7) {
                    LOGGER.error("register service : {} failed 7 times , quit register,please check ! ", service);
                    break;
                }
            }
        }
    }
}
